package com.csi.jf.crucible.ptservice.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import com.chinasofti.ro.bizframework.core.orm.IDAO;
import com.chinasofti.ro.bizframework.core.orm.Page;
import com.chinasofti.ro.bizframework.core.orm.entity.Model;
import com.csi.jf.crucible.api.sonar.SonarApiUtil;
import com.csi.jf.crucible.common.config.JfConstants;
import com.csi.jf.crucible.common.model.JfTUser;
import com.csi.jf.crucible.common.util.FileUtils;
import com.csi.jf.crucible.common.util.LoginUtils;
import com.csi.jf.crucible.common.util.PackageUtils;
import com.csi.jf.crucible.common.util.TimeTool;
import com.csi.jf.crucible.ptservice.model.CodePackages;
import com.csi.jf.crucible.ptservice.model.PrjAssociate;
import com.csi.jf.crucible.ptservice.model.SonarDaily;
import com.csi.jf.crucible.ptservice.model.Sonarservices;
import com.csi.jf.crucible.ptservice.model.ToolServices;
import com.csi.jf.crucible.ptservice.model.ToolservicesStatus;
import com.csi.jf.crucible.ptservice.model.ToolservicesStatusPk;
import com.csi.jf.crucible.ptservice.model.ToolservicesUse;
import com.csi.jf.crucible.ptservice.service.SonarservicesService;

/**
 * <p>Service Impl</p>
 * 
 * @author BizFoundation
 * @version 1.0
 * @since 1.0
 */
public class SonarservicesServiceImpl implements SonarservicesService {

	private IDAO dao;
	private String destPath = "";
	
	public void setDao(IDAO dao) {
		this.dao = dao;
	}

	/**
	 * 根据id查询数据
	 * 
	 * @param id
	 * @return model
	 */
	public Model findCodePacakgeById(Long id) {
		CodePackages codePackages = new CodePackages();
		codePackages.setId(id);
		return (Model) dao.createQuery(codePackages).first();
	}
	
	/**
	 * 分页查询
	 * 
	 * @param sonarservices
	 * @param page 分页
	 * @return
	 */
	public Page findByPage(ToolservicesUse toolservicesUse, Page page) {
		String sql = toolservicesUse.getSql("list", dao.dbMeta());//使用sonarservices.hbm.xml中的id为list的sql查询
		return dao.createNamedQuery(toolservicesUse.getClass(),sql, toolservicesUse).fetch(page);
	}
	
	/**
	 * 批量删除数据
	 * 
	 * @param ids
	 * @return int[] delete records
	 */
	public int[] batchDelete(String ids) {
		Sonarservices sonarservices = new Sonarservices();
		return dao.batchDelete(sonarservices, ids);
	}

	/**
	 * 保存数据
	 * @param Model
	 */
	public void save(Model model) {
		dao.save(model);
	}

	/**
	 * 更新数据
	 * @param Model
	 */
	public void update(Model model) {
		dao.update(model);
	}

    @Override
    public void createWorkspace(Long projectId,SonarDaily sonarDaily) {
        // initialize workspace directory
    	String path = JfConstants.PTS_WORKSPACE_HOME + File.separator + projectId;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //记录日志
        sonarDaily.setCreator(LoginUtils.getLoginUser().getUserName());
        sonarDaily.setCreatdate(TimeTool.getcurrentTimeMillis());
        sonarDaily.setType("创建临时空间");
        String operation = "空间路径为："+path;
        sonarDaily.setOperation(operation);
        save(sonarDaily);       
    }

    @Override
    public void retreiveCodeFromPackage(Long codePackageId,SonarDaily sonarDaily) {
        CodePackages cp = (CodePackages)this.findCodePacakgeById(codePackageId);
        if(cp!=null){
            String fileName = PackageUtils.createPakcageName(cp);
            //unzip file into workspace
            destPath = fileName.substring(0, 2)+JfConstants.PTS_WORKSPACE_HOME + File.separator + cp.getProjectId() + File.separator;
            FileUtils.unzip(fileName,destPath);
            //记录日志
            sonarDaily.setCreator(LoginUtils.getLoginUser().getUserName());
            sonarDaily.setCreatdate(TimeTool.getcurrentTimeMillis());
            sonarDaily.setType("解析代码包到临时空间");
            String operation = "";
            operation +="包名:"+cp.getPackagename()+cp.getExtendName()+"<br>";
            operation +="大小："+cp.getPackagesize()+"<br>";
            sonarDaily.setOperation(operation);
            save(sonarDaily);
        }
    }

    @Override
    public void createSonarProjectCfg(CodePackages cp,PrjAssociate pc,SonarDaily sonarDaily) throws Exception {
        // sonar-project.properties，后面可以考虑使用vm模板进行动态创建
    	String path = JfConstants.PTS_WORKSPACE_HOME + File.separator + pc.getPrjJfId()+File.separator +"sonar-project.properties";
        File f = new File(path);
        if (!f.exists()) {
            f.createNewFile();
        }
        FileWriter fw = new FileWriter(f);
        PrintWriter pw = new PrintWriter(fw);
        String projectKey = pc.getPrjSonarKey();
        String projectName = pc.getPrjCruName();
        String projectVersion = cp.getPackageversion();
        String sources = cp.getSources();
        String binaries = cp.getBinaries();
        String language = cp.getLanguage();
        pw.append("# required metadata\n");
        pw.append("sonar.projectKey=").append(projectKey).append("\n");
        pw.append("sonar.projectName=").append(projectName).append("\n");
        pw.append("sonar.projectVersion=").append(projectVersion).append("\n");
        pw.append("# path to source directories (required)\n");
        pw.append("sonar.sources=").append(sources).append("\n");
        pw.append("# path to project binaries (optional)\n");
        pw.append("sonar.binaries=").append(binaries).append("\n");
        pw.append("# Uncomment this line to analyse a project which is not a java project.\n");
        pw.append("sonar.language=").append(language).append("\n");
        pw.append("# Additional parameters");
        pw.append("sonar.forceAuthentication=true");
        pw.flush();
        pw.close();
        //记录日志
        sonarDaily.setCreator(LoginUtils.getLoginUser().getUserName());
        sonarDaily.setCreatdate(TimeTool.getcurrentTimeMillis());
        sonarDaily.setType("创建sonar-project.properties文件");
        String operation = "";
        operation +="文件路径为:"+path+"内容如下：<br>";
        operation +="sonar.projectKey:"+projectKey+"<br>";
        operation +="sonar.projectName:"+projectName+"<br>";
        operation +="sonar.sources:"+sources+"<br>";
        operation +="sonar.binaries:"+binaries+"<br>";
        operation +="sonar.language:"+language+"<br>";
        sonarDaily.setOperation(operation);
        save(sonarDaily);
    }

    @Override
    public void runSonarRunner(Long codePackageId,SonarDaily sonarDaily) throws Exception{
    	CodePackages cp = (CodePackages)this.findCodePacakgeById(codePackageId);
    	//记录日志
        String operation = "";
        sonarDaily.setCreator(LoginUtils.getLoginUser().getUserName());
        sonarDaily.setCreatdate(TimeTool.getcurrentTimeMillis());
    	sonarDaily.setType("运行sonar-runner.bat");
    	//sonar临时空间的路径
        if(destPath != ""){
        	String path = destPath;
        //需要判断当前操作系统是不是window
        String os = System.getProperties().getProperty("os.name").toUpperCase();
        Runtime runtime = Runtime.getRuntime();
        //windows
        if (os.indexOf("WINDOWS")!= -1){
        	String msg = null; 
            String strCmd = "sonar-runner.bat";//执行shell命令 
            //批量执行cmd命令
            Process pro4 = runtime.exec("cmd /c cd "+ path +" && "+ strCmd);
            BufferedReader br4 = new BufferedReader(new InputStreamReader(pro4 
          	      .getInputStream()));
            while ((msg = br4.readLine()) != null) { 
              System.out.println(msg); 
              //记录日志
              operation +=msg+"<br>";
            }
        }else{
            //linux/unix/other
            String shell = "sonar-runner";//执行shell命令
            Runtime.getRuntime().exec(shell);//通过执行shell命令调用protoc.sh程序
        }}
        //保存日志
        sonarDaily.setOperation(operation);
        save(sonarDaily);
    }

    @Override
    public void getServiceStatus() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void getServiceLogs() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void clearWorkspace(Long projectId,SonarDaily sonarDaily){
        // initialize workspace directory
    	String path = JfConstants.PTS_WORKSPACE_HOME + File.separator
                + projectId;
        FileUtils.delAllFile(path);
        //记录日志
        sonarDaily.setCreator(LoginUtils.getLoginUser().getUserName());
        sonarDaily.setCreatdate(TimeTool.getcurrentTimeMillis());
        sonarDaily.setType("清空临时空间");
        String operation = "空间路径为："+path;
        sonarDaily.setOperation(operation);
        save(sonarDaily);
    }

    @Override
    public void setProjectPermission(PrjAssociate cp) {
        //1-查找项目成员信息
        //List list = apiService.getProjectMembers(projectId);
        List<JfTUser> list = this.getSampleMembers();
        //2-将成员授权可以访问sonar项目
        SonarApiUtil apiUtil = new SonarApiUtil();
        if(list!=null){
            for(int i=0;i<list.size();i++){
            JfTUser user = (JfTUser)list.get(i);
            apiUtil.insertUserPermission("user,codeviewer,issueadmin",
                    user.getUserName(), cp.getPrjSonarKey());
            }
        }
    }
    
    private List<JfTUser> getSampleMembers(){
        List<JfTUser> list = new ArrayList<JfTUser>();
        JfTUser u = new JfTUser();
        u.setUserName("zhangmh");
        list.add(u);
        return list ;
    }
    
    

    @Override
    public PrjAssociate findByPrjID(Long prjID) {
    	PrjAssociate prjAssociate = new PrjAssociate();
    	if(prjID!=null)
        prjAssociate.setPrjJfId(prjID);
    	return (PrjAssociate)dao.createQuery(prjAssociate).first();
    }

	@SuppressWarnings("unchecked")
    @Override
	public List<ToolServices> findAllToolSer() {
		ToolServices toolServices = new ToolServices();
		return (List<ToolServices>)dao.createQuery(toolServices).list();
	}

	@Override
	public ToolservicesUse findToolservicesUse(Long projetID, Long serviceId) {
		ToolservicesUse toolservicesUse = new ToolservicesUse();
		toolservicesUse.setProjectId(projetID);
		toolservicesUse.setServiceId(serviceId);
		return (ToolservicesUse)dao.createQuery(toolservicesUse).first();
	}

	@Override
	public Sonarservices find(Sonarservices sonarservices) {
		return (Sonarservices)dao.createQuery(sonarservices).first();
	}

    @Override
    public String showSonarDashboardUrl(PrjAssociate prjAssociate) {
        //e.g.http://115.29.76.124:9000/dashboard/index/266
        //TODO 根据sonar-project-key查找对应的id，目前没有API可用，需要扩展
        Long sonarPrjId = 0L;
        return SonarApiUtil.SONAR_URL+"/dashboard/index/"+sonarPrjId;
    }

	@Override
	public ToolServices findToolSerByID(Long id) {
		ToolServices temp = new ToolServices();
		temp.setId(id);
		return (ToolServices)dao.createQuery(temp).first();
	}

	@Override
	public List<Model> findSerAllInfo(Long id) {
		List<Model> list = new ArrayList<Model>();
		Sonarservices tempS = new Sonarservices();
		tempS.setId(id);
		Sonarservices sonarSer = (Sonarservices)dao.createQuery(tempS).first();
		CodePackages tempC = new CodePackages();
		tempC.setId(sonarSer.getCodePackageId());
		CodePackages codePack = (CodePackages)dao.createQuery(tempC).first();
		list.add(sonarSer);
		list.add(codePack);
		return list;
	}

    @Override
    public ToolServices findToolServiceById(Long serviceId) {
        ToolServices temp = new ToolServices();
        temp.setId(serviceId);
        return (ToolServices)dao.createQuery(temp).first();
    }

    @Override
    public ToolservicesUse findToolServiceHistoryById(Long serviceHistoryId) {
        ToolservicesUse temp = new ToolservicesUse();
        temp.setId(serviceHistoryId);
        return (ToolservicesUse)dao.createQuery(temp).first();
    }

    @Override
    public ToolservicesStatus findToolServiceStatus(Long projectId,
            Long serviceId) {
        ToolservicesStatus temp = new ToolservicesStatus();
        ToolservicesStatusPk toolservicesStatusPk = new ToolservicesStatusPk();
        toolservicesStatusPk.setProjectId(projectId);
        toolservicesStatusPk.setServiceId(serviceId);
        temp.setToolservicesStatusPk(toolservicesStatusPk );
        return (ToolservicesStatus)dao.createQuery(temp).first();
    }

	@Override
	public Model find(Model model) {
		return (Model)dao.createQuery(model).first();
	}

	@Override
	public List<SonarDaily> findAllSonarDaily(Long serviceuseID) {
		SonarDaily sd = new SonarDaily();
		sd.setServiceusedid(serviceuseID);
		return dao.createQuery(sd).list();
	}
   
    
}